package com.hrm.dao;


import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/** 数据库操作类，提供连接等操作
 * Create by zekdot on 19-6-14.
 */
public abstract class BaseDao<T> {
    //定义数据库相关信息
    private static final String URL="jdbc:mysql://localhost:3306/"; // 数据库地址
    private static final String DATEBASE="hrm?characterEncoding=utf-8";    //数据库名称
    private static final String USERNAME="hrm_admin";   //用户名
    private static final String PASSWORD="123456";   //密码

    private Class<T> entityClass;
    public BaseDao() {
        this.entityClass = null;
        Class<?> c = getClass();
        Type type = c.getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();
            this.entityClass = (Class<T>) parameterizedType[0];
        }
    }
    /**
     * 获取sql形式的变量名
     * @param str Java格式变量名
     * @return
     */
    public String getSqlFieldName(String str){
        for(int i=0;i<str.length();i++){
            if(i!=0 && str.charAt(i) > 'A' && str.charAt(i) < 'Z'){
                str = str.replace(""+str.charAt(i),"_" + (char)(str.charAt(i) - 'A' + 'a'));
            }
        }
        return str.toLowerCase();
    }
    /**
     * 获取表名
     * @return
     */
    private String getTableName(){
        String tableNames[] = entityClass.getTypeName().split("\\.");
        String tableName = tableNames[tableNames.length-1];
        tableName = tableName.substring(0,tableName.length()-6);
        tableName = getSqlFieldName(tableName);
        return tableName;
    }

    /**获得数据库的连接，以进行其他操作
     *
     * @return 数据库连接
     */
    protected Connection getConnect(){
        Connection connection=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            connection = DriverManager.getConnection(URL+DATEBASE,USERNAME,PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 执行sql
     * @param op 执行接口
     * @throws SQLException
     */
    protected void execute(DaoOp op) throws Exception {
        // 获取连接
        Connection connection = getConnect();
        // 执行
        op.execute(connection);
        // 关闭
        connection.close();
    }

    /**
     * 执行查询
     * @param op 执行接口
     * @return 返回结果
     * @throws SQLException
     */
    protected List<T> queryList(DaoOp op) throws Exception {
        // 获取连接
        Connection connection = getConnect();
        // 执行，并获取结果
        List<T> list = op.queryList(connection);
        // 关闭
        connection.close();
        // 返回结果
        return list;
    }

    /**
     * 查询一条
     * @param op 执行结果
     * @return 执行结果
     * @throws SQLException
     */
    protected T queryOne(DaoOp op) throws Exception {
        // 获取连接
        Connection connection = getConnect();
        // 执行，并获取结果
        T item = (T) op.queryOne(connection);
        // 关闭
        connection.close();
        // 返回结果
        return item;
    }

    protected PreparedStatement getPreparedStatement(Connection connection,String sql,Object [] params) throws SQLException {

        // 预准备语句
        PreparedStatement ps = connection.prepareStatement(sql);
        if(params == null)
            return ps;
        int index = 1;
        // 设置参数
        for(int i=0;i<params.length;i++){

            Object param = params[i];
            if(param == null)
                continue;
            if(param.getClass() == Integer.class){
                ps.setInt(index++, (Integer) param);
            }else if(param.getClass() == Double.class){
                ps.setDouble(index++, (Double) param);
            }else if(param.getClass() == String.class){
                ps.setString(index++, (String) param);
            }else if(param.getClass() == Long.class){
                ps.setLong(index++,(Long)param);
            }
        }
        return ps;

    }

    /**
     * 执行sql
     * @param sql SQL语句
     * @param params  参数
     * @throws SQLException
     */
    protected void execute(String sql,Object[] params) throws Exception {
        // 获取连接
        Connection connection = getConnect();
        // 设置准备语句
        PreparedStatement ps = getPreparedStatement(connection,sql,params);

//        System.out.println(ps.toString());
        // 执行
        ps.execute();
        // 关闭
        connection.close();
    }
    /**
     * 根据result获取实体
     * @param resultSet
     * @return
     */
    public Object getEntity(ResultSet resultSet) throws IllegalAccessException, InstantiationException, SQLException {
        // 新建实体类
        Object object = entityClass.newInstance();
        // 获取成员变量
        Field fields[] = entityClass.getDeclaredFields();
        // 处理所有成员变量
        for(Field field:fields){
            // 设置可访问
            field.setAccessible(true);

            if(field.getType().equals(int.class)){
                // 设置int型变量
                field.setInt(object,resultSet.getInt(getSqlFieldName(field.getName())));
            }else if(field.getType().equals(String.class)){
                // 设置String型变量
                field.set(object,resultSet.getString(getSqlFieldName(field.getName())));
            }else if(field.getType().equals(double.class)){
                // 设置String型变量
                field.set(object,resultSet.getDouble(getSqlFieldName(field.getName())));
            }else if(field.getType().equals(Timestamp.class)){
                // 设置timestamp型变量
                field.set(object,resultSet.getTimestamp(getSqlFieldName(field.getName())));
            }else if(field.getType().equals(long.class)){
                field.set(object,resultSet.getLong(getSqlFieldName(field.getName())));
            }
        }
        return object;
    }
    /**
     * 查询一个列表
     * @param sql SQL语句
     * @param params 参数列表
     * @return 返回结果
     * @throws SQLException
     */
    protected List<T> queryList(String sql,Object...params) throws Exception {
        // 获取连接
        Connection connection = getConnect();
        // 设置准备语句
        PreparedStatement ps = getPreparedStatement(connection,sql,params);
        // 获取结果集
        ResultSet res = ps.executeQuery();
        // 新建结果列表
        List<T> list = new ArrayList<>();
        while(res.next()){
            T t = (T) getEntity(res);
            list.add(t);
        }
        // 关闭
        connection.close();
        // 返回结果
        return list;
    }

    /**
     * 查询一条
     * @param sql SQL语句
     * @param params 参数列表
     * @return 执行结果
     * @throws SQLException
     */
    protected T queryOne(String sql,Object...params) throws Exception {
        // 获取连接
        Connection connection = getConnect();
        // 设置准备语句
        PreparedStatement ps = getPreparedStatement(connection,sql,params);
        // 获取结果集
        ResultSet res = ps.executeQuery();
        T t;
        if(res.next()){
            t = (T) getEntity(res);
        }else {
            t = null;
        }
        // 关闭
        connection.close();
        // 返回结果
        return t;
    }
    /**
     * 常规保存方式
     * @param t
     */
    public void save(T t) throws Exception{
        String tableName = getTableName();
        // 构造SQL语句
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("INSERT INTO ").append(tableName).append("(");
        Field[] fields = entityClass.getDeclaredFields();
        Object params[] = new Object[fields.length];
        for(int i=0;i<fields.length;i++){
            fields[i].setAccessible(true);

            params[i] = fields[i].get(t);
        }
        for(int i=0;i<fields.length;i++){
            if(params[i] != null)
                sqlBuilder.append(getSqlFieldName(fields[i].getName())).append(",");
        }
        sqlBuilder.deleteCharAt(sqlBuilder.length()-1);
        sqlBuilder.append(")");
        sqlBuilder.append(" VALUES(");
        for(int i=0;i<fields.length;i++){
            if(params[i] != null)
                sqlBuilder.append("?,");
        }
        sqlBuilder.deleteCharAt(sqlBuilder.length()-1);
        sqlBuilder.append(")");


        execute(sqlBuilder.toString(),params);
    }

    /**
     * 根据主键获取某个对象
     * @param id 主键
     * @param idName id名称
     * @return
     * @throws Exception
     */
    public T get(Object id,String idName) throws Exception {
        String tableName = getTableName();
        String sql = "SELECT * FROM " + tableName + " WHERE " + idName + "=?";
        return queryOne(sql,id);
    }

    /**
     * 删除表中某一个数据
     * @param id 主键
     * @param idName id名称
     */
    public void delete(Object id,String idName) throws Exception {
        String tableName = getTableName();
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("DELETE FROM ").append(tableName).append(" WHERE " + idName + "=?");
        Object[] params = {id};
        execute(sqlBuilder.toString(),params);
    }

    /**
     * 更新数据库中某一个对象
     * @param id 对象主键
     * @param paramMap 需要进行改变的成员-成员值映射
     * @param idName id名称
     */
    public void update(Object id, Map<String,Object> paramMap,String idName) throws Exception {
        String tableName = getTableName();
        // 构造SQL语句
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE ").append(tableName).append(" SET ");
        // 获取Map的键集合
        Set<String> set = paramMap.keySet();

        for(String key:set){
            sqlBuilder.append(getSqlFieldName(key)).append("=").append("?,");
        }
        sqlBuilder.deleteCharAt(sqlBuilder.length()-1);
        sqlBuilder.append(" WHERE " + idName + "=?");

        Object params[] = new Object[set.size()+1];
        int index = 0;
        for(String key:set){
            params[index++] = paramMap.get(key);
        }
        params[index] = id;
//        System.out.println(sqlBuilder.toString());
//        for(Object o:params){
//            System.out.print(o + " ");
//        }
//        System.out.println();
        execute(sqlBuilder.toString(),params);
    }



    /**
     * 获取下一页的对象列表
     * @param lastId
     * @param length
     */
    public List<T> getNextPage(Object lastId,int length,String idName) throws Exception {
        String tableName = getTableName();
        StringBuilder sqlBuilder = new StringBuilder().append("SELECT * FROM " + tableName + " WHERE " + idName + ">? LIMIT ");
        sqlBuilder.append(length);
        Object params[] = {lastId};
        return queryList(sqlBuilder.toString(),params);
    }




    /**
     * 根据主键获取某个对象
     * @param id 主键
     * @return
     * @throws Exception
     */
    public T get(Object id) throws Exception {
        String tableName = getTableName();
        String sql = "SELECT * FROM " + tableName + " WHERE id=?";
        return queryOne(sql,id);
    }
    
    /**
     * 删除表中某一个数据
     * @param id 主键
     */
    public void delete(Object id) throws Exception {
        String tableName = getTableName();
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("DELETE FROM ").append(tableName).append(" WHERE id=?");
        Object[] params = {id};
        execute(sqlBuilder.toString(),params);
    }

    /**
     * 更新数据库中某一个对象
     * @param id 对象主键
     * @param paramMap 需要进行改变的成员-成员值映射
     */
    public void update(Object id, Map<String,Object> paramMap) throws Exception {
        String tableName = getTableName();
        // 构造SQL语句
        StringBuilder sqlBuilder = new StringBuilder();
        sqlBuilder.append("UPDATE ").append(tableName).append(" SET ");
        // 获取Map的键集合
        Set<String> set = paramMap.keySet();

        for(String key:set){
            sqlBuilder.append(getSqlFieldName(key)).append("=").append("?,");
        }
        sqlBuilder.deleteCharAt(sqlBuilder.length()-1);
        sqlBuilder.append(" WHERE id=?");

        Object params[] = new Object[set.size()+1];
        int index = 0;
        for(String key:set){
            params[index++] = paramMap.get(key);
        }
        params[index] = id;
//        System.out.println(sqlBuilder.toString());
//        for(Object o:params){
//            System.out.print(o + " ");
//        }
//        System.out.println();
        execute(sqlBuilder.toString(),params);
    }

    

    /**
     * 获取下一页的对象列表
     * @param lastId
     * @param length
     */
    public List<T> getNextPage(Object lastId,int length) throws Exception {
        String tableName = getTableName();
        StringBuilder sqlBuilder = new StringBuilder().append("SELECT * FROM " + tableName + " WHERE id>? LIMIT ");
        sqlBuilder.append(length);
        Object params[] = {lastId};
        return queryList(sqlBuilder.toString(),params);
    }

}
